import { ref, onMounted, nextTick, watch } from "vue";

export function useNavBarHeight() {
  const navBarHeight = ref(0);

  const updateNavBarHeight = async () => {
    await nextTick();
    const navBarElement = document.querySelector(".van-nav-bar__content");
    if (navBarElement) {
      navBarHeight.value = navBarElement.getBoundingClientRect().height;
    } else {
      // 如果找不到元素，使用默认高度
      navBarHeight.value = 44; // van-nav-bar 的默认高度
    }
  };

  // 监听 DOM 变化，当导航栏显示/隐藏时更新高度
  const observeNavBar = () => {
    const observer = new MutationObserver(() => {
      updateNavBarHeight();
    });

    const targetNode = document.body;
    observer.observe(targetNode, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ["class", "style"]
    });

    return observer;
  };

  onMounted(() => {
    updateNavBarHeight();
    const observer = observeNavBar();
    
    // 清理函数
    return () => {
      observer.disconnect();
    };
  });

  return {
    navBarHeight,
    updateNavBarHeight
  };
} 